<!-- 长租其它 确认费用 -->
<template>
  <a-modal
    v-model:visible="showModal"
    @close="onClose"
    @before-open="onBeforeOpen"
    title="确认费用"
    class="modal-dialog-wrapper"
    unmount-on-close
    :mask-closable="false"
    width="65vw"
  >
    <div class="fee-page">
      <div class="fee-list">
        <div v-for="(item, index) in feeList" :key="index" style="margin: 0 20px">
          <feeitem :fee="item" />
        </div>
        <div class="all-cost">
          <span>合计</span>
          <div class="cost-num">
            <div>{{ costType == 10 ? '应收' : '应付' }}：{{ unitVal(Math.abs(feeCostAmount.receiveAmount), '元') }}</div>
            <div style="margin-top: 16px"
              >{{ costType == 10 ? '待收' : '待付' }}：{{ unitVal(Math.abs(feeCostAmount.receivedNotAmount), '元') }}</div
            >
          </div>
        </div>
      </div>
      <a-divider />
      <page-form :model="form" layout="vertical" ref="formRef" style="margin-top: 40px">
        <page-form-row>
          <page-form-item
            field="actualAmount"
            :label="costName + '金额'"
            :rules="{ required: true, message: '请输入' + costName + '金额' }"
          >
            <i-input-number v-model="form.actualAmount" unit="元" :precision="2" disabled />
          </page-form-item>
          <page-form-item
            field="paymentWay"
            :label="costName + '方式'"
            :rules="{ required: true, message: '请选择' + costName + '方式' }"
            labelTooltipContent="收/付款方式支持在系统管理菜单下的收支账号管理页面进行配置。"
          >
            <a-select
              placeholder="请选择"
              v-model="form.paymentWay"
              @change="typeChange"
              :disabled="disabledCostType"
              :trigger-props="{ updateAtScroll: true, scrollToClose: true }"
              allow-clear
              popup-container="#app"
            >
              <a-option v-for="item in paywayEnum" :key="item.way" :value="item.way" :label="item.wayStr" />
            </a-select>
          </page-form-item>
          <page-form-item v-if="form.paymentWay == -1" field="account" label="结算主体" :rules="{ required: true, message: '请选择' }">
            <a-select
              :placeholder="'请选择'"
              v-model="form.account"
              :trigger-props="{ updateAtScroll: true, scrollToClose: true }"
              allow-clear
              popup-container="#app"
            >
              <a-option v-for="item in accountList" :key="item.id" :value="item.id" :label="item.bank" />
            </a-select>
          </page-form-item>
          <page-form-item
            v-else
            field="account"
            :label="costName + '账号'"
            labelTooltipContent="收/付款账号支持在系统管理菜单下的收支账号管理页面进行配置。"
          >
            <a-select
              :placeholder="!form.paymentWay ? '请先选择' + costName + '方式' : '请选择'"
              v-model="form.account"
              :disabled="!form.paymentWay ? true : false"
              :trigger-props="{ updateAtScroll: true, scrollToClose: true }"
              allow-clear
              popup-container="#app"
            >
              <a-option
                v-for="item in accountList"
                :key="item.id"
                :value="item.id"
                :label="item.account + (item.bank ? '_' + item.bank : '')"
              />
            </a-select>
          </page-form-item>
          <page-form-item
            v-if="form.paymentWay && form.paymentWay != -1"
            field="paymentTime"
            :label="costName + '时间'"
            :rules="[{ required: true, message: '请选择' + costName + '时间', trigger: 'change' }]"
          >
            <i-date-picker
              class="w-full"
              v-model="form.paymentTime"
              show-time
              value-format="YYYY-MM-DD HH:mm:ss"
              :trigger-props="{ updateAtScroll: true, scrollToClose: true }"
              popup-container="#app"
            />
          </page-form-item>
          <page-form-item field="customerName" label="客户名称" :rules="{ required: true, message: '请输入客户名称' }">
            <i-input placeholder="请输入" v-model="form.customerName" :max-length="20" />
          </page-form-item>
          <page-form-item field="customerAccount" :label="costName == '收款' ? '客户付款账号' : '客户收款账号'">
            <i-input placeholder="请输入" v-model="form.customerAccount" :max-length="20" />
          </page-form-item>
          <page-form-item field="settlementRemark" label="结算备注" size="2/3">
            <i-input placeholder="请输入" v-model="form.settlementRemark" :max-length="200" />
          </page-form-item>
        </page-form-row>
      </page-form>
    </div>
    <template #footer>
      <a-space>
        <a-button @click="onClose">关闭</a-button>
        <a-button type="primary" @click="submitFn" :loading="okLoading">确认</a-button>
      </a-space>
    </template>
  </a-modal>

  <qcode-modal v-model:visible="payQCodeModal" @close="payQCodeClose" :details="qrCodeDetails" :from="qrCodeFrom" />
</template>

<script setup name="ShortOrderConfirmFees" lang="ts">
  import feeitem from './comfirm-fee-item.vue'
  import qcodeModal from '@/views/confirmFee/modals/qcode-modal.vue'

  import { Message } from '@arco-design/web-vue'
  import { unitVal } from '@/utils'
  import { getAccountByPageData, getAccountByWayAndType, feetoConfirm, feeSubmit } from '@/api/order/czsOrder'
  import { ref } from 'vue'
  import useUserStore from '@/store/modules/user'

  const userStore = useUserStore()
  const paywayEnum = ref<any>([]) //收付款方式
  const accountList = ref<any>([]) //收付款账号列表
  const costType = ref<any>() // 收支类型 10 收款 20 付款
  const costName = ref('')
  const feeList = ref<any>([]) // 收付款列表
  const feeCostAmount = ref<any>({}) //收付款类型及金额
  const formRef = ref()
  const disabledCostType = ref(false)
  const payQCodeModal = ref(false)
  const form = ref<any>({
    idList: [], //结算单ids
  })

  const onBeforeOpen = () => {
    userStore.setEpDetail()
  }

  defineProps({
    title: {
      type: String,
      default: '确认费用',
    },
  })

  // 打开弹窗
  const okLoading = ref(false)
  const showModal = ref(false)
  const orderDetail = ref<any>({})

  const show = (idList: any, record: any) => {
    console.log('确认费用: ', idList, record)

    // 重置
    resetForm()
    showModal.value = true
    orderDetail.value = record
    form.value.idList = JSON.parse(idList)
    if (form.value.idList) {
      feeConfirm(form.value.idList)
    }
    okLoading.value = false
  }

  const payQCodeClose = () => {
    emit('feepageConfirm')
  }

  const onClose = () => {
    showModal.value = false
    okLoading.value = false
  }
  const resetForm = () => {
    disabledCostType.value = false
    paywayEnum.value = []
    accountList.value = []
    form.value = {}
    okLoading.value = false
  }
  // 去确认
  const feeConfirm = (ids: any) => {
    feetoConfirm({ idList: ids }).then((res: any) => {
      feeCostAmount.value = res.result
      feeList.value = res.result.orderFeeList
      form.value.actualAmount = Math.abs(res.result.receiveAmount) //固定金额，不可修改
      costType.value = res.result.costType
      form.value.recordType = res.result.costType
      form.value.paymentTime = feeList.value && feeList.value.length > 0 ? feeList.value[feeList.value.length - 1].createTime : ''
      form.value.customerName =
        feeList.value && feeList.value.length > 0 ? feeList.value[feeList.value.length - 1].orderInfo.memberName : ''
      if (costType.value == 10) {
        costName.value = '收款'
      } else {
        costName.value = '付款'
      }
      // 押金抵扣为固定收付款方式
      if (feeCostAmount.value.payType != null) {
        disabledCostType.value = true
        form.value.paymentWay = feeCostAmount.value.payType.toString()
      }

      getType(res.result.costType, res.result.orderFeeList)
    })
  }
  // 收付款类型
  const getType = (costType: any, orderFeeList = []) => {
    console.log('getType: ', costType, orderFeeList)

    // 是否包含线下费用
    const is_offline = orderFeeList.every((item: any) => item.feeType == 1)
    console.log('is_offline', is_offline)

    // 是否为收款
    const is_collection = orderFeeList.every((item: any) => item.costType == 10)
    console.log('is_collection', is_collection, form.value.actualAmount)

    // 是否包含租车押金和违章押金
    const is_contain_rent_violation = orderFeeList.some((item: any) => item.feeNameId == 12 || item.feeNameId == 13)
    console.log('is_contain_rent_violation', is_contain_rent_violation)

    let is_show_jialian = false
    if (orderFeeList.length == 1 && is_collection && form.value.actualAmount > 0) {
      is_show_jialian = true
    } else if (orderFeeList.length > 1) {
      if (is_collection && form.value.actualAmount > 0) {
        is_show_jialian = true
      } else if (!is_collection && form.value.actualAmount > 0) {
        is_show_jialian = true
      }
    }
    console.log('is_show_jialian', is_show_jialian)

    const syncInventory: any = userStore.syncInventory

    getAccountByPageData({ type: costType == 10 ? 0 : 1 }).then((res: any) => {
      // 过滤
      var data = res.result

      console.log('getAccountByPageData: ', data, syncInventory.jialianEnabled, form.value.actualAmount)

      data.forEach((i: any) => {
        if (i.way != '1' && i.way != '2' && i.way != '3' && i.way != '5' && disabledCostType.value) {
          paywayEnum.value.push(i)
        } else if (i.way != '1' && i.way != '2' && i.way != '3' && i.way != '4' && i.way != '5' && !disabledCostType.value) {
          paywayEnum.value.push(i)
        }

        /**
         * 不显示嘉联聚合支付
         * syncInventory.jialianEnabled: 0 未开通嘉联聚合支付
         * actualAmount: 收款金额小于等于0
         * is_offline: 不是线下费用时
         * is_show_jialian: 是否显示嘉联聚合支付，默认不显示
         * is_contain_rent_violation: 是否包含租车押金和违章押金
         */
        if (syncInventory.jialianEnabled == 0 || !is_show_jialian || !is_offline || is_contain_rent_violation) {
          paywayEnum.value = paywayEnum.value.filter((el: any) => el.way != '-1')
        }
      })
      if (form.value.paymentWay) {
        typeChange(form.value.paymentWay)
      }
    })
  }
  // 账号
  const typeChange = (e: any) => {
    if (e) {
      form.value.account = ''
    }
    paywayEnum.value.forEach((el: any) => {
      if (el.way == e) {
        getAccountByWayAndType({ way: Number(el.way), type: Number(el.type) }).then((res: any) => {
          if (res.result.length == 1 && form.value.paymentWay == -1) {
            form.value.account = res.result[0].id
          }

          accountList.value = res.result
        })
      }
    })
  }
  defineExpose({
    show,
  })
  const emit = defineEmits(['feepageConfirm'])

  const qrCodeDetails = ref()
  const qrCodeFrom = ref('')

  const submitFn = () => {
    okLoading.value = true
    formRef.value.validate((error: any) => {
      if (!error) {
        const param = {
          ...form.value,
          orderId: orderDetail.value.orderId,
        }
        feeSubmit(param)
          .then((res: any) => {
            if (form.value.paymentWay == -1) {
              qrCodeFrom.value = 'orderConfirmFee'
              qrCodeDetails.value = { qrcodeId: res.result }
              showModal.value = false
              payQCodeModal.value = true
            } else {
              Message.success(res.message)
              showModal.value = false
              emit('feepageConfirm')
            }
          })
          .finally(() => {
            okLoading.value = false
          })
      } else {
        okLoading.value = false
      }
    })
  }
</script>

<style lang="less" scoped>
  .fee-list {
    padding-top: 20px;
    margin-bottom: 80px;
    border: 1px solid #f2f3f5;
  }
  .all-cost {
    font-weight: 600;
    padding: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    background: #f2f3f5;
    height: 100px;
    .cost-num {
      color: #1890ff;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
    }
  }
  // 弹窗添加的样式
  .fee-page {
    position: relative;
    width: 100%;
    max-height: 70vh;

    :deep(.arco-row) {
      margin-left: 0 !important;
      margin-right: 0 !important;
    }
    :deep(.arco-modal-body) {
      padding: 10px 80px !important;
    }
    :deep(.arco-col) {
      padding: 0 10px !important;
    }
  }
</style>
